package com.sharedprint.system.area.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sharedprint.system.area.pojo.AreaInfo;
import com.sharedprint.system.area.service.AreaInfoService;

@Controller
@RequestMapping("/api/areaInfo")
public class AreaInfoController {

	private static final Logger logger = Logger.getLogger("AreaInfoController");

	@Autowired
	private AreaInfoService areaInfoService;

	/**
	 * 获取分页列表
	 * 
	 * @return
	 */
	@RequestMapping("/queryPageList")
	@ResponseBody
	public Map<String, Object> queryPageList(HttpServletRequest req) {
		String areaCode = req.getParameter("areaCode");
		String areaNameLike = req.getParameter("areaNameLike");

		String currentPage = req.getParameter("currentPage");
		String pageSize = req.getParameter("pageSize");
		String orderByValue = req.getParameter("orderByValue");

		List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
		int totalCount = 0;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (currentPage == null || "".equals(currentPage.trim())) {
			currentPage = "0";
		}
		if (pageSize == null || "".equals(pageSize.trim())) {
			pageSize = "10";
		}
		Map<String, Object> searchMap = new HashMap<String, Object>();
		int currentPageIndex = Integer.parseInt(currentPage) * Integer.parseInt(pageSize);
		searchMap.put("currentPageIndex", currentPageIndex);
		searchMap.put("pageSize", Integer.parseInt(pageSize));
		searchMap.put("areaNameLike", areaNameLike);
		searchMap.put("areaCode", areaCode);
		try {
			totalCount = areaInfoService.findCount(searchMap);// 总记录数
			if (totalCount > 0) {
				if (orderByValue == null || "".equals(orderByValue.trim())) {
					searchMap.put("orderByAreaIdDesc", "1");
				}
				areaList = areaInfoService.findPageList(searchMap);
			}
			resultMap.put("currentPage", Integer.parseInt(currentPage) + 1);
			resultMap.put("pageTotal", totalCount);
			resultMap.put("pageList", areaList);
			resultMap.put("success", "1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 初始化添加相关数据
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/initAdd")
	@ResponseBody
	public Map<String, Object> initAdd(HttpServletRequest req) {
		List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> searchMap = new HashMap<String, Object>();
		areaList = areaInfoService.findPageList(searchMap);
		resultMap.put("areaList", areaList);
		resultMap.put("success", "1");
		return resultMap;
	}

	/**
	 * 验证地区编码
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/validAreaCode")
	@ResponseBody
	public boolean validAreaCode(HttpServletRequest req) {
		String areaCode = req.getParameter("areaCode");
		String excludeAreaId = req.getParameter("excludeAreaId");
		logger.info(",areaCode=" + areaCode + ",excludeAreaId=" + excludeAreaId);
		boolean result = false;
		if (areaCode != null && !"".equals(areaCode.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("areaCode", areaCode);
			if (excludeAreaId != null && !"".equals(excludeAreaId.trim())) {
				searchMap.put("excludeAreaId", excludeAreaId);
			}
			int count = areaInfoService.findCount(searchMap);
			if (count == 0) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 验证地区名称
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/validAreaName")
	@ResponseBody
	public boolean validAreaName(HttpServletRequest req) {
		String areaParentCode = req.getParameter("areaParentCode");
		String areaName = req.getParameter("areaName");
		String excludeAreaId = req.getParameter("excludeAreaId");
		logger.info(",areaName=" + areaName + ",areaParentCode=" + areaParentCode + ",excludeAreaId=" + excludeAreaId);
		boolean result = false;
		if (areaName != null && !"".equals(areaName.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("areaName", areaName);
			searchMap.put("areaParentCode", areaParentCode);
			if (excludeAreaId != null && !"".equals(excludeAreaId.trim())) {
				searchMap.put("excludeAreaId", excludeAreaId);
			}
			int count = areaInfoService.findCount(searchMap);
			if (count == 0) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 保存地区信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest req) {
		String areaCode = req.getParameter("areaCode");
		String areaName = req.getParameter("areaName");
		String areaParentCode = req.getParameter("areaParentCode");
		String sortNo = req.getParameter("sortNo");
		String description = req.getParameter("description");
		String userId = req.getHeader("userId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (areaCode != null && !"".equals(areaCode.trim()) && areaName != null && !"".equals(areaName.trim())
				&& sortNo != null && !"".equals(sortNo.trim()) && userId != null && !"".equals(userId.trim())) {
			AreaInfo areaInfo = new AreaInfo();
			areaInfo.setAreaCode(areaCode);
			areaInfo.setAreaName(areaName);
			areaInfo.setAreaParentCode(areaParentCode);
			areaInfo.setSortNo(Integer.parseInt(sortNo));
			areaInfo.setAreaParentCode(areaParentCode);
			areaInfo.setOprId(Integer.parseInt(userId));
			areaInfo.setDescription(description);
			try {
				int success = areaInfoService.saveInfo(areaInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "保存失败");
				}
			} catch (Exception e) {
				logger.info("保存异常=" + e.getMessage());
				e.printStackTrace();
				resultMap.put("msg", "保存异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 获取修改相关信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/initUpdate")
	@ResponseBody
	public Map<String, Object> initUpdate(HttpServletRequest req) {
		String areaId = req.getParameter("areaId");
		logger.info(",areaId=" + areaId);

		Map<String, Object> areaMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
		if (areaId != null && !"".equals(areaId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("areaId", areaId);
			areaList = areaInfoService.findPageList(searchMap);
			areaMap = areaList.get(0);
			areaList = areaInfoService.findPageList(null);
		}
		resultMap.put("areaList", areaList);
		resultMap.put("areaMap", areaMap);
		resultMap.put("success", "1");
		return resultMap;
	}

	/**
	 * 修改信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(HttpServletRequest req) {
		String areaId = req.getParameter("updateAreaId");
		String areaCode = req.getParameter("updateAreaCode");
		String areaName = req.getParameter("updateAreaName");
		String areaParentCode = req.getParameter("updateAreaParentCode");
		String sortNo = req.getParameter("updateSortNo");
		String description = req.getParameter("updateDescription");
		String userId = req.getHeader("userId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");

		if (areaCode != null && !"".equals(areaCode.trim()) && areaName != null && !"".equals(areaName.trim())
				&& sortNo != null && !"".equals(sortNo.trim()) && userId != null && !"".equals(userId.trim())
				&& areaId != null && !"".equals(areaId.trim())) {
			AreaInfo areaInfo = new AreaInfo();
			areaInfo.setAreaId(Integer.parseInt(areaId));
			areaInfo.setAreaCode(areaCode);
			areaInfo.setAreaName(areaName);
			areaInfo.setAreaParentCode(areaParentCode);
			areaInfo.setSortNo(Integer.parseInt(sortNo));
			areaInfo.setAreaParentCode(areaParentCode);
			areaInfo.setOprId(Integer.parseInt(userId));
			areaInfo.setDescription(description);
			try {
				int success = areaInfoService.updateInfo(areaInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "修改失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("修改异常=" + e.getMessage());
				resultMap.put("msg", "修改异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 删除信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest req) {
		String areaCode = req.getParameter("areaCode");
		logger.info(",areaCode=" + areaCode);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (areaCode != null && !"".equals(areaCode.trim())) {
			// 判断是否有下级
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("areaParentCode", areaCode);
			int count = areaInfoService.findCount(searchMap);
			searchMap.remove("areaParentCode");
			if (count == 0) {
				searchMap.put("areaCode", areaCode);
				try {
					int success = areaInfoService.deleteInfo(searchMap);
					if (success > 0) {
						resultMap.put("success", "1");
					} else {
						resultMap.put("msg", "删除失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.info("删除异常=" + e.getMessage());
					resultMap.put("msg", "删除异常");
				}
			} else {
				resultMap.put("msg", "该地区存在子地区,不允许删除!");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 获取详情
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/detail")
	@ResponseBody
	public Map<String, Object> detail(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String areaId = req.getParameter("areaId");
		logger.info(",areaId=" + areaId);

		Map<String, Object> areaMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
		if (areaId != null && !"".equals(areaId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("areaId", areaId);
			areaList = areaInfoService.findPageList(searchMap);
			areaMap = areaList.get(0);
		}
		resultMap.put("areaMap", areaMap);
		resultMap.put("success", "1");
		return resultMap;
	}
}
